package handle

import (
	"encoding/json"
	"server/game/model"
	"server/share"

	"github.com/hwcer/cosgo/schema"
	"github.com/hwcer/cosgo/times"
	"github.com/hwcer/cosgo/values"
	"github.com/hwcer/yyds/context"
	"github.com/hwcer/yyds/options"
)

func init() {
	//Register(gm)
	Register(oauth)
	Register(roles)
	Register(search)
}

// oauth 登录
func oauth(c *context.Context) interface{} {
	guid := c.GUid()
	reply := values.Values{}
	//查询角色列表
	rs, err := getRoles(guid)
	if err != nil {
		return err
	}
	reply["roles"] = rs
	reply["TimeZone"] = times.GetTimeZone()     //时区
	reply["TimeZero"] = options.GetServerTime() //开服时间
	reply["TimeReset"] = share.TimeReset        //每日切换天的偏移量
	reply[AutoSelectCharacter] = 0
	//自动登录
	if auto := c.GetInt32(AutoSelectCharacter); auto > 0 && len(rs) > 0 {
		role := rs[0]
		if _, err = Online(c, guid, role.Uid); err != nil {
			return err
		} else {
			reply[AutoSelectCharacter] = 1
		}
	}
	if cookie := c.GetMetadata(options.ServiceMetadataCookie); cookie != "" {
		s := make(map[string]string)
		if err = json.Unmarshal([]byte(cookie), &s); err == nil {
			reply["cookie"] = map[string]string{
				"key": s["name"],
				"val": s["value"],
			}
		}
	}

	return reply
}

// pwd 进入GM模式
// secret string 秘钥
//func gm(c *context.Context) any {
//	secret := c.GetString("secret")
//	if secret == "" {
//		return c.Errorf(0, "secret empty")
//	}
//	if secret != options.Options.Developer {
//		return c.Errorf(0, "secret error")
//	}
//	c.SetMetadata(options.ServiceMetadataDeveloper, "1")
//	return "success"
//}

type searchPlayer struct {
	share.Player
	Guid string `json:"guid"`
}

// search 通过uid查询角色信息
// uid string 用户账户直接登录，不需要授权，仅仅DEBU状态有效
func search(c *context.Context) interface{} {
	uid := c.GetString("uid")
	if uid == "" {
		return c.Errorf(0, "uid empty")
	}
	p := &searchPlayer{}

	fields := p.GetDBFields()
	fields = append(fields, "guid")
	if tx := db.Model(&model.Role{}).Select(fields...).Where(uid).Find(p); tx.Error != nil {
		return tx.Error
	} else if tx.RowsAffected == 0 {
		return c.Errorf(0, "no such role")
	}
	return p

}

// 查询本服角色
func roles(c *context.Context) interface{} {
	if rows, err := getRoles(c.GUid()); err != nil {
		return err
	} else {
		return rows
	}

}

// 查询本服角色
func getRoles(guid string) ([]*share.Player, error) {
	if guid == "" {
		return nil, context.Error("guid empty")
	}
	var rows []*share.Player
	sch, err := schema.Parse(rows)
	if err != nil {
		return nil, err
	}

	var field []string
	for _, f := range sch.Fields {
		field = append(field, f.DBName())
	}

	if err = db.Model(&model.Role{}).Select(field...).Where("guid = ?", guid).Find(&rows).Error; err != nil {
		return nil, err
	}
	return rows, nil
}
